<?php

namespace App\Logics;

use App\Models\Admin;
use App\Models\SiteDomain;
use App\Service\Base\Logic;
use App\Service\Curl;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Config;

class WordLogic extends Logic
{


    // 生成word
    public function makeWord()
    {
        $option = $this->option();
        $date   = $option->getData('date', '', 'trim');
        $path   = app()->basePath().'/public/';

        $wordFile = $path.'易见舆情日报.docx';
        $newfile  = $path.'date/易见舆情日报'.$date.'.docx';
        if(!is_file($newfile)){
            // php artisan command:make-word 2024-3-5
            Artisan::call('command:make-word', ['date' => $date]);
        }

        return true;
    }

    // 下载word
    public function downWord()
    {
        // word 信息
        $option   = $this->option();
        $date     = $option->getData('date', '', 'trim');
        $path     = app()->basePath().'/public/';
        $wordFile = $path.'易见舆情日报.docx';
        $wordFile = $path.'date/易见舆情日报'.$date.'.docx';
        $downfile = $path.'date/易见舆情日报.docx';

        // 股票信息
        $url  = 'https://xinsanban.eastmoney.com/api/QuoteCenter/stock/getstockquote?code=400132';
        $curl = new Curl();
        $res  = $curl->url($url)->request();
        $res  = json_decode($res, true);
        if($res){
            $stock = $res['result'][0] ?? $res['result'];
        }
        if(empty($stock)){
            $stock = ['Close' => '-', 'Change' => '-', 'ChangePercent' => '-', 'MarketValue' => '-',];
        }

        // 方案：直接用模板替换
        $processor = new \PhpOffice\PhpWord\TemplateProcessor($wordFile);
        $processor->setValue('stock_price', $stock['Close']);
        $processor->setValue('stock_market', $stock['MarketValue'] == '-' ? $stock['MarketValue'] : round($stock['MarketValue'] / 100000000, 2));
        if(($stock['Close'] == '-') && ($stock['Change'] == '-')){
            $processor->setValue('stock_change', '-');
            $processor->setValue('stock_date', '非交易日');
        } else{
            $processor->setValue('stock_date', '交易日');
            $processor->setValue('stock_change', ($stock['ChangePercent'] > 0 ? '+' : '').$stock['ChangePercent']);
        }

        // 保存
        $processor->saveAs($downfile);

        return response()->download($downfile, $date.'易见舆情日报.docx');
    }

}


